package com.leetcode.June;

/**
 * @Description: 最大子数组和
 * @Author: Mr.Fxy
 * @CreateTime: 2024-07-04 21:38
 */
public class maxSum {

    public static int maxSubArray(int[] nums) {
        if (nums == null || nums.length == 0) return 0;

        int currentSum = nums[0];
        int maxSum = nums[0];

        for (int i = 1; i < nums.length; i++) {
            // 如果当前子数组和为负数，抛弃之前的子数组，开始一个新的子数组
            currentSum = Math.max(nums[i], currentSum + nums[i]);
            maxSum = Math.max(maxSum, currentSum);
        }

        return maxSum;
    }

    public static void main(String[] args) {
        int[] nums = {5,4,-1,7,8};
        int i = maxSubArray(nums);
        System.out.println(i);
    }
}
